<template>
  <el-drawer
    v-model="showDrawer"
    :title="$t('修改登录密码')"
    size="420px"
    @close="emit('close')"
  >
    <el-form
      ref="formRef"
      :model="form"
      status-icon
      :rules="rules"
      label-position="top"
    >
      <el-form-item prop="current_password" :label="$t('当前密码')">
        <el-input
          v-model="form.current_password"
          :placeholder="$t('请输入当前密码')"
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="new_password" :label="$t('新登录密码')">
        <el-input
          type="password"
          v-model="form.new_password"
          :placeholder="$t('请输入新登录密码')"
          show-password
          size="large"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="confirm_password" :label="$t('确认密码')">
        <el-input
          type="password"
          v-model="form.confirm_password"
          :placeholder="$t('请再次输入密码')"
          show-password
          size="large"
        >
        </el-input>
      </el-form-item>
      <!-- <el-form-item prop="code" :label="$t('验证码')">
        <div class="flex items-center justify-between flex-1">
          <el-input
            v-model="form.code"
            :placeholder="$t('验证码')"
            size="large"
          >
          </el-input>

          <el-button
            size="large"
            plain
            type="primary"
            class="w-40 ml-4"
            @click="handleCaptcha"
            v-if="!codesms.disabled"
          >
            {{ $t("获取验证码") }}
          </el-button>
          <el-button
            size="large"
            type="primary"
            class="w-40 ml-4"
            v-else
            disabled
          >
            {{ codesms.count }}{{ $t("秒后重新获取") }}
          </el-button>
        </div>
      </el-form-item> -->
      <el-form-item>
        <div class="justify-around w-full my-5 text-left">
          <el-button
            type="primary"
            size="large"
            class="w-full"
            @click="onSubmit"
            :loading="loading"
          >
            {{ $t("提交") }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { reactive, ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { ChangeNewPassword, emailSendApi } from "@/api/login/index";
import { useUserStore } from "@/store/modules/user";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["close"]);
const showDrawer = ref(false);
watch(
  () => props.show,
  (newVal) => {
    showDrawer.value = newVal;
  }
);
const formRef = ref("");
const form = reactive({
  current_password: "",
  new_password: "",
  confirm_password: "",
  code: "",
});
const loading = ref(false);

const router = useRouter();

const useUser = useUserStore();

const codesms = reactive({
  disabled: false,
  total: 60,
  count: 0,
});

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error(t("输入确认密码")));
  } else if (value !== form.new_password) {
    callback(new Error(t("确认密码和新密码一致")));
  } else {
    callback();
  }
};
// 校验
const rules = computed(() => {
  return {
    current_password: [
      { required: true, message: t("请输入当前密码"), trigger: "blur" },
    ],
    new_password: [
      { required: true, message: t("请输入新登录密码"), trigger: "blur" },
    ],
    confirm_password: [
      { required: true, validator: validatePass2, trigger: "blur" },
    ],
    // code: [{ required: true, message: t("请输入验证码"), trigger: "blur" }],
  };
});
// 倒计时
const timerHandle = () => {
  codesms.count = codesms.total;
  codesms.disabled = true;

  let timer = setInterval(() => {
    if (codesms.count > 1 && codesms.count <= codesms.total) {
      codesms.count--;
    } else {
      codesms.disabled = false;
      clearInterval(timer);
    }
  }, 1000);
};

//发送验证码
const handleCaptcha = async () => {
  try {
    timerHandle();

    const res = await emailSendApi({
      email: useUser.userInfo.userName,
      code_type: "change_password",
    });
    ElMessage({
      type: "success",
      message: t("发送验证码成功"),
    });
    // console.log(res);
  } catch (error) {}
};

//修改密码
const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      try {
        loading.value = true;
        // 1.调用修改密码接口
        const res = await ChangeNewPassword(form);
        ElMessage({
          message: t("修改密码成功"),
          type: "success",
        });
        useUser.clearUserInfo();
        router.replace("/login");
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    })
    .catch((error) => {
      loading.value = false;
      // console.log(error);
    });
};
</script>
